package cqut.wys.service;

import cqut.wys.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.ColumnMapRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * @author wuyoushan
 * @date 2017/3/10.
 */
@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 获取用户列表
     */
    @Override
    public List<Map<String,Object>> listUser(){
        String sql="SELECT id,name,gender,age FROM user";
        RowMapper<Map<String, Object>> rowMapper=new ColumnMapRowMapper();
        List<Map<String,Object>> list=jdbcTemplate.query(sql, rowMapper);
        return list;
    }

    /**
     * 获取用户信息
     *
     * @param id userId
     */
    @Override
    public User getUser(Long id){
        String sql="select id,name,gender,age from user where id=?";
        User user=(User)jdbcTemplate.queryForObject(sql,new Object[]{id},new BeanPropertyRowMapper(User.class));
        return user;
    }


    /**
     * 添加用户
     *
     * @param user user
     */
    @Override
    public boolean saveUser(User user){
        String sql=String.format("insert into user(name,gender,age) values('%s','%s',%d)",
                user.getName(),user.getGender(),user.getAge());
        jdbcTemplate.execute(sql);
        return true;
    }

    /**
     * 更新用户
     *
     * @param user user
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateUser(User user){
        String sql=String.format("update user set name='%s',gender='%s',age=%d where id=%d",
                user.getName(),user.getGender(),user.getAge(),user.getId());
        int rows=jdbcTemplate.update(sql);
        if(rows>0){
            return true;
        }
        return false;
    }


    /**
     * 删除用户
     *
     * @param id user id
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean removeUser(Long id){
        String sql=String.format("delete from user where id=%d",id);
        jdbcTemplate.execute(sql);
        return true;
    }
}
